package com.woniuxy.member.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.cloud.mall95.log.Log;
import com.woniuxy.coupon.client.CouponQueryClient;
import com.woniuxy.coupon.client.result.CouponDto;
import com.woniuxy.food.client.foodskuclient.FoodSkuQueryClient;
import com.woniuxy.food.client.foodspuclient.FoodSpuQueryClient;
import com.woniuxy.food.client.result.FoodSkuClientDto;
import com.woniuxy.food.client.result.FoodSpuClientDto;
import com.woniuxy.member.app.apiImpl.util.RequestUtil;
import com.woniuxy.member.app.config.AliyunOss;
import com.woniuxy.member.app.config.CheckImage;
import com.woniuxy.member.app.config.WebUtil;
import com.woniuxy.member.client.MemberManageClient;
import com.woniuxy.member.client.param.*;
import com.woniuxy.member.common.MemberResultCode;
import com.woniuxy.member.infra.model.ExchangeCoupon;
import com.woniuxy.member.infra.model.ExchangeFood;
import com.woniuxy.member.service.ExchangeCouponService;
import com.woniuxy.member.service.ExchangeFoodService;
import com.woniuxy.member.service.MemberService;
import com.woniuxy.member.service.dto.FilesReturnDto;
import com.woniuxy.member.service.dto.MemberDto;
import com.woniuxy.member.service.util.JwtUtil;
import com.woniuxy.member.service.util.RedisUtil;
import com.woniuxy.store.client.StoreInfoClient;
import com.woniuxy.store.client.result.StoreInfoDto;
import exception.MallException;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import result.CommonResultCodeEnum;
import result.Result;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/member")
@RestController
public class MemberManageApiImpl implements MemberManageClient {
    @Autowired
    private MemberService memberService;
    @Autowired
    private ExchangeFoodService exchangeFoodService;
    @Autowired
    private ExchangeCouponService exchangeCouponService;
    @Autowired
    private FoodSkuQueryClient foodSkuQueryClient;
    @Autowired
    private FoodSpuQueryClient foodSpuQueryClient;
    @Autowired
    private CouponQueryClient couponQueryClient;
    @Autowired
    private RedissonClient redissonClient;

    @Log("用户扫商家码注册或者登录")
    @Override
    public Result loginStore(@Valid AddMemberParam addMemberParam) {
        MemberDto memberDto = memberService.addAndLoginMember(addMemberParam.getWechatNum()
                , addMemberParam.getOpenId()
                , addMemberParam.getPhone()
                , addMemberParam.getUserName()
                , addMemberParam.getStoreId()
                , addMemberParam.getMemberImg());
        HashMap<String, Object> body = new HashMap<>();
        body.put("memberId",memberDto.getMemberId());
        body.put("storeId",memberDto.getStoreId());
        Integer minites=30;
        String accessToken = JwtUtil.createToken(body, minites);
        String refreshToken = JwtUtil.createToken(body,8*60);
        RBucket<Object> bucket = redissonClient.getBucket(accessToken);
        bucket.set(refreshToken,8*60*60, TimeUnit.SECONDS);
        memberDto.setAccessToken(accessToken);
        return Result.success(memberDto);
    }
    @Log("用户扫餐桌码注册或者登录")
    @Override
    public Result loginTable(@Valid AddMembersParam addMembersParam) {
        MemberDto memberDto = memberService.loginTable(addMembersParam.getTableId(),
                addMembersParam.getWechatNum()
                , addMembersParam.getOpenId()
                , addMembersParam.getPhone()
                ,addMembersParam.getDiningPerson()
                , addMembersParam.getUserName()
                , addMembersParam.getStoreId()
                , addMembersParam.getMemberImg());
        HashMap<String, Object> body = new HashMap<>();
        body.put("memberId",memberDto.getMemberId());
        body.put("storeId",memberDto.getStoreId());
        body.put("tableId",addMembersParam.getTableId());
        Integer minites=30;
        String accessToken = JwtUtil.createToken(body, minites);
        String refreshToken = JwtUtil.createToken(body,8*60);
        RBucket<Object> bucket = redissonClient.getBucket(accessToken);
        bucket.set(refreshToken,8*60*60, TimeUnit.SECONDS);
        memberDto.setAccessToken(accessToken);
        return Result.success(memberDto);
    }

    @Log("用户积分兑换菜品")
    @Override
    public Result exchangeFood(Integer exchangeFoodId) {
        memberService.exchangeFood(RequestUtil.getMemberId(),exchangeFoodId,RequestUtil.getTableId());
        return Result.success("积分兑换菜品成功");
    }
    @Log("用户积分兑换优惠卷")
    @Override
    public Result exchangeCoupon(Integer exchangeCouponId) {
        memberService.exchangeCoupon(RequestUtil.getMemberId(),exchangeCouponId);
        return Result.success("积分兑换优惠卷成功");
    }


    @Log("用户上传图片")
    @Override
    public Result uploadState(MultipartFile[] files) throws IOException {
        AliyunOss aliyunOss = new AliyunOss();
        ArrayList<FilesReturnDto> paths = new ArrayList<>();
        if (files==null||files.length==0){
            throw new MallException("图片为空", CommonResultCodeEnum.INVALID_PARAM);
        }
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            if (!CheckImage.isImage(file)) {
                throw new MallException(MemberResultCode.FILE_IS_NOT_AN_IMAGE);
            }
            String s = UUID.randomUUID().toString();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            String name=s+fileType;
            String path = aliyunOss.ossUpload(file,name);
            FilesReturnDto dto = new FilesReturnDto();
            dto.setFilePath(path);
            dto.setOldFileName(originalFilename.substring(0,originalFilename.lastIndexOf(".")));
            dto.setFileSuffix(fileType);
            dto.setFileName(s);
            dto.setSize(file.getSize());
            paths.add(dto);
        }
        return Result.success(paths);
    }
    @Log("商家添加可兑换菜品")
    @Override
    public Result addMemberFood(@Valid AddMemberFoodParam addMemberFoodParam) {
        Result<FoodSkuClientDto> foodSkuClientDtoResult = foodSkuQueryClient.searchFoodSkuById(addMemberFoodParam.getSkuId());
        if (foodSkuClientDtoResult.getData()==null){
            throw new MallException("sku不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        Integer spuId = foodSkuClientDtoResult.getData().getSpuId();
        Result<FoodSpuClientDto> foodSpuClientDtoResult = foodSpuQueryClient.searchFoodSpuBySkuId(spuId);
        if (foodSpuClientDtoResult.getData()==null){
            throw new MallException("spu不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        if (foodSpuClientDtoResult.getData().getStoreId()!=addMemberFoodParam.getStoreId()) {
            throw new MallException("添加失败",CommonResultCodeEnum.INVALID_PARAM);
        }
        ExchangeFood exchangeFood = new ExchangeFood();
        exchangeFood.setScore(addMemberFoodParam.getScore());
        exchangeFood.setSkuId(foodSkuClientDtoResult.getData().getSkuId());
        exchangeFood.setSkuName(foodSkuClientDtoResult.getData().getSkuName());
        exchangeFood.setMainPic(foodSkuClientDtoResult.getData().getMainPic());
        exchangeFoodService.save(exchangeFood);
        return Result.success();
    }
    @Log("商家添加可兑换优惠卷")
    @Override
    public Result addMemberCoupon(@Valid AddMemberCouponParam addMemberCouponParam) {
        Result<CouponDto> couponDtoResult = couponQueryClient.queryCouponByCouponId(addMemberCouponParam.getCouponId());
        if (couponDtoResult.getData()==null){
            throw new MallException("优惠卷不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        if (couponDtoResult.getData().getStoreId()!=addMemberCouponParam.getStoreId()){
            throw new MallException("优惠卷不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        if (!couponDtoResult.getData().getCouponState().equals("ON")){
            throw new MallException("优惠卷未启用",CommonResultCodeEnum.INVALID_PARAM);
        }
        ExchangeCoupon exchangeCoupon = new ExchangeCoupon();
        exchangeCoupon.setCouponId(couponDtoResult.getData().getCouponId());
        exchangeCoupon.setCouponName(couponDtoResult.getData().getCouponName());
        exchangeCoupon.setScore(addMemberCouponParam.getScore());
        exchangeCouponService.save(exchangeCoupon);
        return Result.success();
    }
    @Log("商家修改可兑换菜品")
    @Override
    public Result modifyMemberFood(@Valid ModifyMemberFoodParam modifyMemberFoodParam) {
        ExchangeFood exchangeFood = exchangeFoodService.getById(modifyMemberFoodParam.getExchangeFoodId());
        if (exchangeFood==null){
            throw new MallException("可兑换菜品不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        Result<FoodSpuClientDto> foodSpuClientDtoResult = foodSpuQueryClient.searchFoodSpuBySkuId(exchangeFood.getSkuId());
        if (foodSpuClientDtoResult.getData().getStoreId()!=modifyMemberFoodParam.getStoreId()) {
            throw new MallException("修改菜品失败",CommonResultCodeEnum.INVALID_PARAM);
        }
        exchangeFood.setScore(modifyMemberFoodParam.getScore());
        exchangeFoodService.updateById(exchangeFood);
        return Result.success();
    }
    @Log("商家修改可兑换优惠卷")
    @Override
    public Result modifyMemberCoupon(@Valid ModifyMemberCouponParam modifyMemberCouponParam) {
        ExchangeCoupon exchangeCoupon = exchangeCouponService.getById(modifyMemberCouponParam.getExchangeCouponId());
        if (exchangeCoupon==null){
            throw new MallException("优惠卷不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        Result<CouponDto> couponDtoResult = couponQueryClient.queryCouponByCouponId(exchangeCoupon.getCouponId());
        if (couponDtoResult.getData().getStoreId()!=modifyMemberCouponParam.getStoreId()) {
            throw new MallException("优惠卷修改失败",CommonResultCodeEnum.INVALID_PARAM);
        }
        exchangeCoupon.setScore(modifyMemberCouponParam.getScore());
        exchangeCouponService.updateById(exchangeCoupon);
        return Result.success();
    }
    @Log("商家删除可兑换菜品")
    @Override
    public Result delMemberFood(Integer storeId, Integer exchangeFoodId) {
        ExchangeFood exchangeFood = exchangeFoodService.getById(exchangeFoodId);
        if (exchangeFood==null){
            throw new MallException("可兑换菜品不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        Result<FoodSpuClientDto> foodSpuClientDtoResult = foodSpuQueryClient.searchFoodSpuBySkuId(exchangeFood.getSkuId());
        if (foodSpuClientDtoResult.getData().getStoreId()!=storeId) {
            throw new MallException("删除菜品失败",CommonResultCodeEnum.INVALID_PARAM);
        }
        exchangeFoodService.removeById(exchangeFoodId);
        return Result.success();
    }
    @Log("商家删除可兑换优惠卷")
    @Override
    public Result delMemberCoupon(Integer storeId, Integer exchangeCouponId) {
        ExchangeCoupon exchangeCoupon = exchangeCouponService.getById(exchangeCouponId);
        if (exchangeCoupon==null){
            throw new MallException("优惠卷不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        Result<CouponDto> couponDtoResult = couponQueryClient.queryCouponByCouponId(exchangeCoupon.getCouponId());
        if (couponDtoResult.getData().getStoreId()!=storeId) {
            throw new MallException("优惠卷删除失败",CommonResultCodeEnum.INVALID_PARAM);
        }
        exchangeCouponService.removeById(exchangeCouponId);
        return Result.success();
    }
}
